package org.jtb.mensawotd;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.MenuItemCompat;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class DetailsActivity extends Activity {
	private static final int SET_TEXT_MSG = 0;
	private static final int FETCH_ERROR_MSG = 1;
	private static final int SET_AUDIO_VISIBLE = 2;
	private static final int SET_AUDIO_CLICKABLE = 3;
	private static final int SET_AUDIO_IMAGE = 4;
	private static final int SET_HISTORY_ENABLED = 5;
	private static final int SET_AUDIO_ENABLED = 6;
	private static final int SET_AUDIO_PLAY = 7;

	static final int HISTORY_DIALOG = 0;

	private String fetcherUrl = MensaWotdUrl.TODAY;
	private List<HistoryItem> items = null;
	private Prefs prefs;
	private AlertDialog historyDialog = null;
	private ImageButton audioButton = null;
	private MensaWotdParser parser = null;
	private MenuItem historyMenuItem = null;
	private ProgressBar audioProgress = null;

	private static class SetText {
		int id;
		String text;

		public SetText(int id, String text) {
			this.id = id;
			this.text = text;
		}
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SET_TEXT_MSG:
				setText((SetText) msg.obj);
				break;
			case FETCH_ERROR_MSG:
				Toast.makeText(DetailsActivity.this, "Error fetching word!",
						Toast.LENGTH_LONG).show();
				SetText st = new SetText(R.id.details_word_text,
						"Fetch error ...");
				setText(st);
				break;
			case SET_AUDIO_VISIBLE:
				// audioButton.setVisibility(View.VISIBLE);
				break;
			case SET_AUDIO_IMAGE:
				int id = (Integer) msg.obj;
				audioButton.setImageResource(id);
				break;
			case SET_HISTORY_ENABLED:
				boolean b = (Boolean) msg.obj;
				if (historyMenuItem != null) {
					historyMenuItem.setEnabled(b);
				}
				break;
			case SET_AUDIO_ENABLED:
				audioButton.setEnabled((Boolean) msg.obj);
				break;
			case SET_AUDIO_CLICKABLE:
				audioButton.setClickable((Boolean) msg.obj);
				break;
			case SET_AUDIO_PLAY:
				setAudioPlay((Boolean) msg.obj);
				break;
			}
		}
	};

	private void setAudioPlay(boolean state) {
		if (state) {
			audioButton.setVisibility(View.INVISIBLE);
			audioProgress.setVisibility(View.VISIBLE);
		} else {
			audioButton.setVisibility(View.VISIBLE);
			audioProgress.setVisibility(View.INVISIBLE);
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.details);

		prefs = new Prefs(this);

		audioButton = (ImageButton) findViewById(R.id.details_audio_button);
		audioButton.setEnabled(false);
		audioButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				setAudioPlay(true);

				Executor ex = Executors.newSingleThreadExecutor();
				ex.execute(new Runnable() {

					public void run() {
						final MediaPlayer mediaPlayer = new MediaPlayer();
						try {
							mediaPlayer.reset();
							mediaPlayer.setDataSource(parser.getMp3());
							mediaPlayer.prepare();
							mediaPlayer
									.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

										public void onCompletion(MediaPlayer mp) {
											mediaPlayer.release();
											handler.sendMessage(handler
													.obtainMessage(
															SET_AUDIO_PLAY,
															false));
										}
									});
							mediaPlayer.start();
						} catch (IllegalStateException e) {
							Log.e("mensawotd", "error streaming audio", e);
							mediaPlayer.release();
							handler.sendMessage(handler.obtainMessage(
									SET_AUDIO_PLAY, false));
						} catch (IOException e) {
							Log.e("mensawotd", "error streaming audio", e);
							mediaPlayer.release();
							handler.sendMessage(handler.obtainMessage(
									SET_AUDIO_PLAY, false));
						} catch (IllegalArgumentException e) {
							Log.e("mensawotd", "error streaming audio", e);
							mediaPlayer.release();
							handler.sendMessage(handler.obtainMessage(
									SET_AUDIO_PLAY, false));
						}
					}
				});

			}
		});

		audioProgress = (ProgressBar) findViewById(R.id.details_audio_progress);

		setVolumeControlStream(AudioManager.STREAM_MUSIC);
	}

	@Override
	protected void onResume() {
		super.onResume();
		load();
	}

	void load() {
		Toast.makeText(this, "Fetching word, please wait ...",
				Toast.LENGTH_LONG).show();

		new AsyncTask<Void, Void, MensaWotdParser>() {

			@Override
			protected MensaWotdParser doInBackground(Void... params) {
				Fetcher fetcher = null;
				try {
					fetcher = new Fetcher(fetcherUrl);
				} catch (MalformedURLException e) {
					handler.sendEmptyMessage(FETCH_ERROR_MSG);
					Log.e("mensawotdwidget", "error fetching wotd page", e);
					return null;
				} catch (IOException e) {
					handler.sendEmptyMessage(FETCH_ERROR_MSG);
					Log.e("mensawotdwidget", "error fetching wotd page", e);
					return null;
				}
				MensaWotdParser parser = new MensaWotdParser(
						fetcher.getContent());
				return parser;
			}

			@Override
			protected void onPostExecute(MensaWotdParser parser) {
				DetailsActivity.this.parser = parser;

				if (parser == null) {
					Toast.makeText(DetailsActivity.this,
							"Error fetching word!", Toast.LENGTH_LONG).show();
					SetText st = new SetText(R.id.details_word_text,
							"Fetch error ...");
					setText(st);
					return;
				}

				if (parser.getWord() == null) {
					Toast.makeText(DetailsActivity.this,
							"Error fetching word!", Toast.LENGTH_LONG).show();
					SetText st = new SetText(R.id.details_word_text,
							"Fetch error ...");
					setText(st);
					return;
				}

				audioButton.setEnabled(true);
				prefs.addHistory(parser.getWord(), parser.getUrl(), parser
						.getDate().getTime());

				items = prefs.getHistory();
				if (historyMenuItem != null) {
					historyMenuItem.setEnabled(true);
				}

				setText(new SetText(R.id.details_word_text, parser.getWord()));
				setText(new SetText(R.id.details_pronunciation_text,
						parser.getPronunciation()));
				setText(new SetText(R.id.details_meaning_text,
						parser.getMeaning()));

				// setWebViewData(new
				// WebViewData(R.id.details_etymology_webview,
				// parser.getEtymology()));
				setText(new SetText(R.id.details_etymology_text,
						parser.getEtymology()));
				// setWebViewData(new WebViewData(R.id.details_usage_webview,
				// parser.getUsage()));
				setText(new SetText(R.id.details_usage_text, parser.getUsage()));
			}
		}.execute();
	}

	void setText(SetText st) {
		TextView tv = (TextView) findViewById(st.id);
		tv.setText(Html.fromHtml(st.text));
	}

	public boolean onCreateOptionsMenu(final Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.detail_menu, menu);

		historyMenuItem = menu.findItem(R.id.history_item);
		historyMenuItem
				.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {

					public boolean onMenuItemClick(MenuItem item) {
						showDialog(HISTORY_DIALOG);
						return true;
					}
				});
		if (items != null) {
			historyMenuItem.setEnabled(true);
		}
		MenuItemCompat.setShowAsAction(historyMenuItem,
				MenuItemCompat.SHOW_AS_ACTION_ALWAYS);

		MenuItem mi;

		mi = menu.findItem(R.id.help_item);
		mi.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {

			public boolean onMenuItemClick(MenuItem item) {
				view("http://code.google.com/p/mensawotdwidget-android/wiki/Help");
				return true;
			}
		});
		MenuItemCompat.setShowAsAction(mi,
				MenuItemCompat.SHOW_AS_ACTION_NEVER);

		mi = menu.findItem(R.id.report_item);
		mi.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {

			public boolean onMenuItemClick(MenuItem item) {
				view("http://code.google.com/p/mensawotdwidget-android/issues/list");
				return true;
			}
		});
		MenuItemCompat.setShowAsAction(mi,
				MenuItemCompat.SHOW_AS_ACTION_NEVER);

		return true;
	}

	private void view(String url) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setData(Uri.parse(url));
		startActivity(intent);
	}

	void setFetcherUrl(String fetcherUrl) {
		this.fetcherUrl = fetcherUrl;
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case HISTORY_DIALOG:
			if (historyDialog == null) {
				AlertDialog.Builder builder = new HistoryDialogBuilder(this,
						items);
				historyDialog = builder.create();
			}
			return historyDialog;
		}
		return null;
	}

}
